import type { ProFormInstance } from '@ant-design/pro-form';
import ProForm, {
  ProFormSelect,
  ProFormSwitch,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-form';
import { Card, Col, Form, message, Row, Space, Tag } from 'antd';
import React, { useRef, useState } from 'react';
import { useModel, useRequest } from 'umi';
import UserAuthLogTable from './components/UserAuthLogTable';
import UserDeviceTable from './components/UserDeviceTable';
import UserLoginLogTable from './components/UserLoginLogTable';

import * as c from '@/services/consts';
import * as api from '@/services/user';
import * as utils from '@/utils/utils';
import { PageContainer } from '@ant-design/pro-components';
import { useMatch } from '@umijs/max';

const UserForm: React.FC = (props: any) => {
  // const { match } = props;
  // let userId = match.params.id;

  const match = useMatch({ path: '/customer/user/update/:id' });
  let userId = match?.params?.id;
  if (!userId) {
    userId = '';
  }

  const [current, setCurrent] = useState<API.UserModel | undefined>(undefined);
  const formRef = useRef<ProFormInstance>();

  const { hasRight } = useModel('useAuthModel');

  const { getProduct, getProductOptions } = useModel(
    'useGlobalModel',
    (model) => ({
      getProduct: model.getProduct,
      getProductOptions: model.getProductOptions,
    }),
  );

  const productOptions = getProductOptions(false);
  const userAreaOptions = c.getAllAreas(true);

  const { loading } = useRequest(async () => {
    return loadData();
  });

  const loadData = async () => {
    const result = await api.get(userId);
    if (result.success === true && result.data) {
      const product = getProduct(result.data.productId);
      result.data.productName = product?.name;

      setCurrent(result.data);
    }

    return Promise.resolve({
      loading: false,
    });
  };

  const handleFormSubmit = async (record: API.UserModel) => {
    // console.log('record', record);
    // console.log('formRef.checkedRightIds: ', checkedRightIds);

    let result: API.Result;

    result = await api.update({
      ...current,
      ...record,
    });

    if (result && result.success === true) {
      message.success('提交成功');
      //history.push('/user/user');
    }
  };

  const renderExpireTime = (record?: API.UserModel) => {
    if (!record || !record.serviceType) {
      return <></>;
    }
    if (record.serviceType.expireDays < 1) {
      return (
        // <Tag color="error" key={record.serviceType.id}>
        //   {utils.formatUtcToLocal(record.serviceType.expireTime)}
        // </Tag>
        <span style={{ color: '#ff4d4f' }}>
          {utils.formatUtcToLocal(record.serviceType.expireTime)}
        </span>
      );
    } else if (
      record.serviceType.expireDays >= 1 &&
      record.serviceType.expireDays <= 7
    ) {
      return (
        <span style={{ color: '#faad14' }}>
          {utils.formatUtcToLocal(record.serviceType.expireTime)}
        </span>
      );
    } else {
      return (
        <span style={{ color: '' }}>
          {utils.formatUtcToLocal(record.serviceType.expireTime)}
        </span>
      );
    }
  };

  const renderAuthInfo = (record?: API.UserModel) => {
    if (!record || !record.serviceType) {
      return null;
    }

    const st = record.serviceType;

    return (
      <>
        <Tag
          color={
            st.memberLevel > c.MemberLevel.Free.value ? 'success' : 'default'
          }
        >
          {st.name}
        </Tag>
        {renderExpireTime(record)}
      </>
    );
  };

  const renderSubInfo = (record?: API.UserModel) => {
    if (!record || !record.subscribeStatus) {
      return null;
    }

    const subInfo = record.subscribeStatus;
    if (subInfo.subscribeType == c.SubscribeType.Subscribe) {
      return (
        <>
          ({subInfo.serviceTypeName}){subInfo.serviceSetName} -{' '}
          {subInfo.subscribeStatus}
        </>
      );
    }

    return null;
  };

  return (
    <PageContainer>
      {loading && <Card style={{ minHeight: 468 }} loading={loading} />}
      {!loading && (
        <Card>
          <ProForm<API.UserModel>
            formRef={formRef}
            layout="horizontal"
            style={{ margin: 'auto', marginTop: 8, maxWidth: 600 }}
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 18 }}
            initialValues={current ? current : { status: true }}
            omitNil={false}
            submitter={{
              render: (props, doms) => {
                return (
                  <Row>
                    <Col span={18} offset={4}>
                      <Space>
                        {doms[1]}
                        {doms[0]}
                      </Space>
                    </Col>
                  </Row>
                );
              },
            }}
            onFinish={handleFormSubmit}
          >
            <ProFormSelect
              name="productId"
              label="产品"
              options={productOptions}
              readonly={true}
            />
            <ProFormText name="username" label="用户名" readonly />
            <ProFormText name="accountKey" label="Key" readonly />
            <Form.Item label="当前授权">{renderAuthInfo(current)}</Form.Item>
            <Form.Item label="当前订阅">{renderSubInfo(current)}</Form.Item>
            <ProFormSwitch name="whitelistUser" label="白名单用户" />
            <ProFormSwitch name="testUser" label="测试组用户" />
            <ProFormSelect
              name="userArea"
              label="指定国家地区"
              options={userAreaOptions}
            />
            <ProFormSelect
              name={['config', 'smartMode']}
              label="智能模式"
              options={c.UserConfigSmartMode}
            />
            <ProFormSwitch name={['config', 'debugMode']} label="调试模式" />
            <ProFormSelect
              name={['config', 'logLevel']}
              label="日志级别"
              options={c.UserConfigLogLevel}
            />
            <ProFormSwitch name="status" label="状态" />
            <ProFormTextArea name="remark" label="备注" />
          </ProForm>
        </Card>
      )}

      {hasRight('user_devicelist') && <UserDeviceTable userId={userId} />}
      {hasRight('userauthlog_list') && <UserAuthLogTable userId={userId} />}
      {hasRight('userloginlog_list') && (
        <UserLoginLogTable accountKey={current?.accountKey} />
      )}
    </PageContainer>
  );
};

export default UserForm;
